﻿using FairyGUI;
using FairyGUI.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using WgFrame.Net;

public class SocialPanel : BasePopupPanel
{
    private const int MAX_CHAT_COUNT = 50;

    private GList lsChat;
    private GList lsChatChannel;
    private GTextInput inputChatText;

    public override void Init()
    {
        base.Init();

        frame = view.GetChild("n1").asCom;

        GComponent panelChat = frame.GetChild("n1").asCom;
        lsChat = panelChat.GetChild("n10").asList;
        lsChatChannel = panelChat.GetChild("n9").asList;
        inputChatText = panelChat.GetChild("n5").asTextInput;
        panelChat.GetChild("n6").asButton.onClick.Add(OnSendChatClick);


        MsgListenerMgr.AddMsgListener(MsgListenerType.Chat, OnChatMsg);
    }

    public override void Dispose()
    {
        MsgListenerMgr.RemoveMsgListener(MsgListenerType.Chat, OnChatMsg);
        base.Dispose();
    }

    protected override GComponent CreateView()
    {
        return UIPackage.CreateObject("Main", "panel_social1").asCom;
    }

    private void OnChatMsg(object[] para)
    {
        Dictionary<byte, object> parameters = (Dictionary<byte, object>)para[0];

        string msg1 = (string)parameters[2];
        string msg2 = (string)parameters[3];
        string[] sp1 = msg1.Split(',');

        if (lsChat.numChildren >= MAX_CHAT_COUNT)
        {
            lsChat.RemoveChildToPoolAt(0);
        }
        GComponent cptChatMsg = lsChat.AddItemFromPool().asCom;

        GRichTextField rtfHead = cptChatMsg.GetChild("n0").asRichTextField;
        rtfHead.color = CommonUtil.Golden;

        HtmlParseOptions options = rtfHead.richTextField.htmlParseOptions;
        options.linkColor = CommonUtil.Golden;

        rtfHead.SetVar("name", sp1[0]).SetVar("dujie", sp1[1]).FlushVars();

        GTextField tfMsg = cptChatMsg.GetChild("n1").asTextField;
        tfMsg.text = msg2;

        lsChat.ScrollToView(lsChat.numChildren - 1);
    }

    private void OnSendChatClick(EventContext context)
    {
        if (string.IsNullOrEmpty(inputChatText.text))
        {
            return;
        }

        int dujieLv = 0;
        if (GameNetwork.Player.FightHeroMgr.TryGetPlayerHero(out Hero hero))
        {
            dujieLv = hero.DuJieLevel;
        }
        string msg1 = string.Format("{0},{1}", GameNetwork.Player.Name, CommonUtil.GetDuJieName(dujieLv));
        string msg2 = inputChatText.text;
        RequestHelper.SendChatRequest("public", msg1, msg2);
        inputChatText.text = "";
    }

}
